package biolabs.util;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class FilteringIterable<E> implements Iterable<E> {
	
	private static class FilteringIterator<E> implements Iterator<E> {

		private final Filter<E> filter;
		private final Iterator<E> it;
		private E next;
		
		public FilteringIterator(Iterator<E> i, Filter<E> f){
			this.it = i;
			this.filter = f;
		}

		private E findNext(){
			while(it.hasNext()){
				E e = it.next();
				if(filter.allows(e))
					return e;
			}
			return null;
		}

		@Override
		public boolean hasNext() {
			if(next == null)
				next = findNext();
			return next != null;
		}

		@Override
		public E next() {
			E res;
			if(next != null){
				res = next;
				next = null;
			} else
				res = findNext();

			if(res == null)
				throw new NoSuchElementException();

			return res;
		}

		@Override
		public void remove() {
			throw new UnsupportedOperationException();
		}
	}

	private final Iterable<E> coll;
	private final Filter<E> filter;

	public FilteringIterable(Iterable<E> coll, Filter<E> filter){
		this.coll = coll;
		this.filter = filter;
	}

	@Override
	public Iterator<E> iterator() {
		return new FilteringIterator<E>(coll.iterator(), filter);
	}
}
